import tkinter as tk
import tkinter.filedialog as tkFileDialog

from native.common.control import Control


class FileSelector(Control):
    def __init__(self, root, title="", on_selected_ok=None, on_selected_failed=None):
        self._label = tk.Label(root, text=title)
        self._entry = tk.Entry(root)
        self._button = tk.Button(root)

        self.__on_selected_ok = on_selected_ok
        self.__on_selected_failed = on_selected_failed

        self.__file_types = [("all", "*.*"),]


    def file_types(self):
        return self.__file_types
    def insert_file_types(self, index, label, pattern):
        return self.__file_types.insert(index, (label, pattern))

    def on_load(self):
        self.__selected_file_path = tk.StringVar()
        self._entry["textvariable"] = self.__selected_file_path

        self._button["text"] = "..."
        self._button["command"] = self.__on_selecting

    def selected_file_path(self):
        return self.__selected_file_path.get()

    def __on_selecting(self):
        file_selected = tkFileDialog.askopenfile(filetypes=self.__file_types)
        if file_selected is not None:
            self.__selected_file_path.set(file_selected.name)
            self.on_selected_ok(file_selected.name)

            if self.__on_selected_ok is not None:
                self.__on_selected_ok(self.__selected_file_path.get())
        else:
            self.on_selected_failed()

            if self.__on_selected_failed is not None:
                self.__on_selected_failed()

    def text(self):
        return self.__selected_file_path.get()

    #override
    def on_selected_ok(self, file_path):
        #print(f"{file_path}")
        pass

    #override
    def on_selected_failed(self):
        #print("select file failed")
        pass
